package cc.vv.party.service.impl;

import cc.vv.party.beans.model.Image
import cc.vv.party.beans.model.PovertyAlleviationVillage;
import cc.vv.party.beans.model.Team
import cc.vv.party.beans.model.UserRole
import cc.vv.party.beans.vo.ImageVO
import cc.vv.party.beans.vo.PovertyAlleviationVillageVO
import cc.vv.party.beans.vo.TeamVO
import cc.vv.party.beans.vo.UserVO
import cc.vv.party.service.PovertyAlleviationVillageService;
import cc.vv.party.common.base.BaseServiceImpl;
import cc.vv.party.common.constants.StatusCode
import cc.vv.party.common.ext.uuid
import cc.vv.party.exception.BizException
import cc.vv.party.mapper.*
import cc.vv.party.param.PovertyAlleviationVillageEditParam
import com.baomidou.mybatisplus.mapper.EntityWrapper
import commonx.core.content.transfer
import commonx.core.content.transferEntries
import org.apache.commons.collections.CollectionUtils
import org.apache.commons.lang.StringUtils
import org.apache.commons.lang.Validate
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional
import java.util.*
import kotlin.collections.ArrayList
import kotlin.collections.HashMap
import kotlin.streams.toList

/**
 * <p>
 * 扶贫行政村信息 服务实现类
 * </p>
 *
 * @author Gyb
 * @since 2018-10-12
 */
@Service
open class PovertyAlleviationVillageServiceImpl : BaseServiceImpl<PovertyAlleviationVillageMapper, PovertyAlleviationVillage>(), PovertyAlleviationVillageService {

    @Autowired
    lateinit var teamMapper: TeamMapper

    @Autowired
    lateinit var imageMapper: ImageMapper

    @Autowired
    lateinit var roleMapper: RoleMapper

    @Autowired
    lateinit var userRoleMapper: UserRoleMapper

    @Transactional(rollbackFor = [(Exception::class)])
    override fun edit(param: PovertyAlleviationVillageEditParam, userId: String): Boolean {
        var entity: PovertyAlleviationVillage
        if(StringUtils.isBlank(param.id)){
            entity = param.transfer()
            entity.id = uuid()

            if(StringUtils.isNotBlank(param.parentId)){
                var parent = super.selectById(param.parentId) ?: throw BizException(StatusCode.MESSAGE_NOT_EXIST)
                entity.path = parent.path.plus("/").plus(entity.id)
            } else {
                entity.path = entity.id
            }

            entity.createUser = userId
            super.insert(entity)
        } else {
            entity = super.selectById(param.id) ?: throw BizException(StatusCode.MESSAGE_NOT_EXIST)

            if(StringUtils.isNotBlank(param.villageName)) entity.villageName = param.villageName
            if(StringUtils.isNotBlank(param.mobile)) entity.mobile = param.mobile
            if(StringUtils.isNotBlank(param.addr)) entity.addr = param.addr
            if(StringUtils.isNotBlank(param.mobile)) entity.mobile = param.mobile
            super.updateById(entity)

            imageMapper.delete(EntityWrapper<Image>().where("associa_id = {0}", entity.id).and("type = {0}", 4))
        }

        if(CollectionUtils.isNotEmpty(param.imgList)){
            for(str in param.imgList!!){
                var image = Image()
                image.associaId = entity.id
                image.url = str
                image.type = Integer(4)
                image.url = str
                imageMapper.insert(image)
            }
        }

        return true
    }

    override fun deletePovertyAlleviationVillage(id: String): Boolean {
        var entity = super.selectById(id) ?: throw BizException(StatusCode.MESSAGE_NOT_EXIST)

        var array = entity.path!!.split("/")
        if(array.size == 3){
            //关联队伍信息未删除
            var teamList = teamMapper.selectList(EntityWrapper<Team>().eq("village", id))
            if(CollectionUtils.isNotEmpty(teamList)){
                val role = roleMapper.getByType("team")
                val adminAccountList = teamList.stream().map { it.mobile }.toList()

                userRoleMapper.delete(EntityWrapper<UserRole>().eq("role_id", role.id).`in`("user_account", adminAccountList))
            }
        } else {
            val villageList = super.selectList(EntityWrapper<PovertyAlleviationVillage>().eq("parentId", id))
            if(CollectionUtils.isNotEmpty(villageList)){
                throw BizException(StatusCode.MESSAGE_EXIST.statusCode, "请先删除子节点后，进行该操作")
            }
        }
        return super.deleteById(id)
    }

    override fun info(id: String): PovertyAlleviationVillageVO {
        var result: PovertyAlleviationVillageVO
        var entity = super.selectById(id) ?: throw BizException(StatusCode.MESSAGE_NOT_EXIST)
        result = entity.transfer()

        var imgList = imageMapper.selectList(EntityWrapper<Image>().where("associa_id = {0}", entity.id).and("type = {0}", 4))
        if(CollectionUtils.isNotEmpty(imgList)){
            result.imgList = imgList.stream().map { it.url!! }.toList()
        }
        return result
    }

    override fun getCurrentUserVillage(account: String): PovertyAlleviationVillageVO {
        return baseMapper.getCurrentUserVillage(account)
    }

    override fun message(villageId: String): PovertyAlleviationVillageVO {
        var entity = super.selectById(villageId) ?: throw BizException(StatusCode.MESSAGE_NOT_EXIST)
        var message = entity.transfer<PovertyAlleviationVillageVO>()

        var teamList = teamMapper.selectList(EntityWrapper<Team>().where("village = {0}", villageId))
        if(CollectionUtils.isNotEmpty(teamList)){
            var map = HashMap<String, ArrayList<Team>>()
            for(team in teamList){
                var list: ArrayList<Team>
                if(map.containsKey(team.teamType)){
                    list = map.get(team.teamType)!!
                    list.add(team)
                    map[team.teamType!!] = list
                } else {
                    list = ArrayList()
                    list.add(team)
                }
                map[team.teamType!!] = list
            }

            //第一书记
            if(map.containsKey("0")){
                message.secretary = map["0"]!![0].transfer()
            }

            //村两委班子
            if(map.containsKey("1")){
                message.twoCommittee = map["1"]!!.transferEntries<TeamVO>() as ArrayList
            }

            //扶贫工作队
            if(map.containsKey("2")){
                message.taskForceList = map["2"]!!.transferEntries<TeamVO>() as ArrayList
            }

            //驻村干部
            if(map.containsKey("3")){
                message.villageCadreList = map["3"]!!.transferEntries<TeamVO>() as ArrayList
            }

            var imageList = imageMapper.selectList(EntityWrapper<Image>().where("associa_id = {0}", villageId).and("type = {0}", 4))
            if(CollectionUtils.isNotEmpty(imageList)) {
                message.imgList = imageList.stream().map { it.url!! }.toList()
            }
        }
        return message
    }

    override fun child(parentId: String?): List<PovertyAlleviationVillageVO> {
        var wrapper = EntityWrapper<PovertyAlleviationVillage>()
        if(StringUtils.isNotBlank(parentId)){
            wrapper.where("parent_id = {0}", parentId)
        } else {
            wrapper.where("parent_id is null")
        }

        var list = super.selectList(wrapper)
        if(CollectionUtils.isNotEmpty(list)) return list.transferEntries<PovertyAlleviationVillageVO>() as ArrayList
        return Collections.emptyList()
    }

    override fun treeList(): List<PovertyAlleviationVillageVO> {
        var list = super.selectList(EntityWrapper<PovertyAlleviationVillage>())

        var imgList = imageMapper.selectList(EntityWrapper<Image>().eq("type", 4))
        var imgMapList = HashMap<String, List<String>>()
        if(CollectionUtils.isNotEmpty(imgList)){
            for(temp in imgList){
                var list = if(imgMapList.containsKey(temp.associaId)){
                    imgMapList[temp.associaId] as ArrayList<String>
                } else {
                    ArrayList()
                }
                list.add(temp.url!!)
                imgMapList[temp.associaId!!] = list
            }
        }

        return if(CollectionUtils.isNotEmpty(list)){
            //找出所有顶级节点
            var result = list.stream().filter{it.parentId.isNullOrBlank()}.toList().transferEntries<PovertyAlleviationVillageVO>() as ArrayList<PovertyAlleviationVillageVO>

            //调用递归方法组装树
            for(temp in result){
                temp.imgList = imgMapList[temp.id]
                recursiveTree(temp, list, imgMapList)
            }

            result
        } else {
            Collections.emptyList()
        }
    }

    fun recursiveTree(parent: PovertyAlleviationVillageVO, list: List<PovertyAlleviationVillage>, imgMapList: HashMap<String, List<String>>): PovertyAlleviationVillageVO {
        Objects.requireNonNull(list)
        var childList = ArrayList<PovertyAlleviationVillageVO>()
        for(temp in list){
            var tempConversion = temp.transfer<PovertyAlleviationVillageVO>()
            tempConversion.imgList = imgMapList[temp.id]
            if(tempConversion.parentId == parent.id){
                childList.add(tempConversion)
                recursiveTree(tempConversion, list, imgMapList)
            }
        }
        parent.child = childList
        return parent
    }


}
